<?php
echo "步骤2: 初始化客户数据\n";
echo "这可能需要一些时间，请耐心等待...\n\n";

$pdo = new PDO('mysql:host=localhost;dbname=oa5;charset=utf8mb4', 'root', '123456', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$start = time();

// 1. 更新会员状态
echo "1. 更新会员状态...\n";
$sql = "UPDATE oa_customer
SET is_member = CASE
    WHEN EXISTS (
        SELECT 1 FROM oa_contract
        WHERE customer_id = oa_customer.id
        AND cate_id IN (1, 2, 10, 13)
        AND end_time > UNIX_TIMESTAMP()
        AND delete_time = 0
    ) THEN 1 ELSE 0
END";
$pdo->exec($sql);
echo "   ✓ 会员状态更新完成\n";

// 2. 更新合同数据
echo "2. 更新合同数据...\n";
$sql = "UPDATE oa_customer
SET
    contract_num = (
        SELECT COUNT(*) FROM oa_contract
        WHERE customer_id = oa_customer.id AND delete_time = 0
    ),
    contract_amount = (
        SELECT IFNULL(SUM(cost), 0) FROM oa_contract
        WHERE customer_id = oa_customer.id AND delete_time = 0
    )";
$pdo->exec($sql);
echo "   ✓ 合同数据更新完成\n";

// 3. 更新案件数据
echo "3. 更新案件数据...\n";
$sql = "UPDATE oa_customer
SET
    case_num = (
        SELECT COUNT(*) FROM oa_lawcase
        WHERE customer_id = oa_customer.id AND delete_time = 0
    ),
    case_processing = (
        SELECT COUNT(*) FROM oa_lawcase
        WHERE customer_id = oa_customer.id AND status IN (1,2,3) AND delete_time = 0
    ),
    case_finished = (
        SELECT COUNT(*) FROM oa_lawcase
        WHERE customer_id = oa_customer.id AND status IN (4,5) AND delete_time = 0
    )";
$pdo->exec($sql);
echo "   ✓ 案件数据更新完成\n";

$duration = time() - $start;
echo "\n✓ 数据初始化完成，耗时: " . $duration . " 秒\n\n";

// 显示统计信息
echo "数据统计:\n";
$stmt = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(is_member = 1) AS members,
        SUM(contract_num > 0) AS has_contracts,
        SUM(case_num > 0) AS has_cases
    FROM oa_customer WHERE delete_time = 0
");
$stats = $stmt->fetch();
echo "  总客户数: " . number_format($stats['total']) . "\n";
echo "  会员客户: " . number_format($stats['members']) . "\n";
echo "  有合同客户: " . number_format($stats['has_contracts']) . "\n";
echo "  有案件客户: " . number_format($stats['has_cases']) . "\n";
